<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-10-23
 * Time: 下午4:44
 */
//session_start();
include('../common/autoload.php');

use pft\Member\MemberAccount;
use pft\Sms\SmsNotify;
use pft\notice;
$action = trim($_REQUEST['action']);
$token = $_REQUEST['token'];
$soap = SoapInit::GetSoapInside();
$mem = new MemberAccount($GLOBALS['le'], $_SESSION['memberID']);
switch($action) {
    case 'warning':
        if(!$_SESSION['memberID'])  exit('登录超时');
        $threshold = $_POST['v'] + 0;
        if($threshold<0) exit('资金不能小于0');
        $sql_mobile = "SELECT mobile,account FROM pft_member WHERE id={$_SESSION['memberID']} limit 1";
        $GLOBALS['le']->query($sql_mobile);
        $GLOBALS['le']->fetch_assoc();
        if($threshold>0 && $GLOBALS['le']->f('mobile')=='') exit('预警信息发送至账号绑定的手机，请先绑定手机');
        echo (MemberAccount::setBankroll($_SESSION['memberID'],$threshold*100)) ? 'ok':'失败';
        break;
    //忘记密码，分手机验证和
    case 'ChkPassport':
        $passport = trim($_REQUEST['mobile']);
        $passport = safetxt($passport);
        $chk_res = $mem->chkPassport($passport,$dname);
        if($chk_res){
            echo '{"status":"ok","msg":"存在该账号","mobile":"'.$chk_res.'"}';
			exit;
        }
        else {
            echo '{"status":"fail","msg":"不存在该账号"}';
        }
        break;
	//验证手机存在性，存在获取账号信息  author by Tong.BC
	case 'chkAndGet':
		$passport = trim($_REQUEST['mobile']);
        $passport = safetxt($passport);
        $chk_res = $mem->_chkPassport($passport);
		// 手机注册了普通会员
		if($chk_res && $chk_res['dtype']>5){
			$chk_res['ajaxStatus']='3';
			echo json_encode($chk_res);
			exit;
		}
        if($chk_res){
			$memid = $_SESSION['memberID'];
			$r=$mem->_SearchDistor($passport,'0,1', $memid,null,'mobile');
			$chk_res=$r[0];
			$chk_res['ajaxStatus']='2';
			$chk_res['ajaxMsg']='存在该账号';
			$chk_res['ajaxMobile']=$chk_res['mobile'];
			echo json_encode($chk_res);
            exit;
        }
        echo '{"status":"1","msg":"不存在该账号"}';
		break;
	case 'chkAndGet2':
		$passport = trim($_REQUEST['mobile']);
        $passport = safetxt($passport);
        $result = $mem->memberSearch($passport);
		$response = array();
		$response['code'] = 101; // 不存在
		$response['data'] = $result;
		if(count($result)){
			$response['code'] = 100; // 存在
			if($result['status']!=0) $response['code'] = 103;// 禁用或删除
			if($result['dtype']==5) $response['code'] = 102;// 散客
		}
		echo json_encode($response);
		break;
    //验证手机存在性，存在获取账号信息  author by Tong.BC
	case 'chkAndGetReg':
		$passport = trim($_REQUEST['mobile']);
        $passport = safetxt($passport);
        $chk_res = $mem->_chkPassport($passport);
        
		if($chk_res && !$_SESSION['memberID']){
            //是散客的情况 account是手机号  4
            // 手机注册了供应商/分销商   3
			$chk_res['ajaxStatus']= ismobile($chk_res['account']) ? '4':'3';
			echo json_encode($chk_res);
			exit;
            
		}elseif($_SESSION['memberID']){
			$memid = $_SESSION['memberID'];
//			$r=$mem->_SearchDistor($passport,'0,1', $memid,null,'mobile');//这个是搜名字的
            $r=$mem->searchDistorByM($passport,'0,1', $memid,null,'mobile');
            if($r[0]){
                $chk_res=$r[0];
                $chk_res['ajaxStatus']='2';
                $chk_res['ajaxMsg']='存在该账号';
                $chk_res['ajaxMobile']=$chk_res['mobile'];
                echo json_encode($chk_res);
            }else
                echo '{"status":"1","msg":"不存在该账号"}';
        }
        else {
            echo '{"status":"1","msg":"不存在该账号"}';
        }
		break;
    case 'SendVcode':
//        print_r($_SERVER);exit;
        if(isset($_REQUEST['chk_user']) && $_REQUEST['chk_user']==1) {
            $sql_mobile = "SELECT mobile,account FROM uu_member WHERE id={$_SESSION['memberID']}";
            $GLOBALS['le']->query($sql_mobile);
            $GLOBALS['le']->fetch_assoc();
            $mobile = $GLOBALS['le']->f('mobile');
            //$stype = 'register';
        } else {
            $mobile = safetxt($_REQUEST['mobile']);
            $email  = is_email($_REQUEST['email']) ? $_REQUEST['email'] : '';
        }
        $stype = safetxt($_REQUEST['stype']);
        $sms_tpl_file = TPLPATH."sms/{$stype}.txt";
       // echo $sms_tpl_file;
        //TODO:账号验证，正式上线后开启
        if($stype=='register') {
            if($mem->chkPassport($mobile ,$GLOBALS['le'])) {
                exit('{"status":"fail","msg":"该手机号用户已注册票付通会员，请尝试更换其它号码，若有疑问请联系我们！"}');
            }
        }
        if(file_exists($sms_tpl_file)) {
            $tpl = file_get_contents($sms_tpl_file);
        }
        else {
            exit ('{"status":"fail","msg":"短信模板不存在！"}');
        }
        //echo $tpl;
        $time_diff = $_SERVER['REQUEST_TIME']-$_SESSION['timer'];
        if(!isset($_SESSION['timer']) || $time_diff>5) {
            $r = MemberAccount::sendVcode($mobile, $tpl, $soap, true);
            //TODO::发送邮件验证啊
            if (!empty($email) && isset($_SESSION['vcode'])) {
                include '../module/mail/mail.php';
                $mail = Mail::to($email)
                    ->from('票付通-www.12301.cc <12301@12301.cc>')
                    ->title('票付通平台注册验证码')
                    ->content("<p>欢迎使用票付通平台。验证码【<strong style='color:#F00'>{$_SESSION['vcode']}</strong>】，输入验证继续完成操作。</p>");
                $mailer = new Nette\Mail\SmtpMailer($mail->config);
                try {
                    $mailer->send($mail);
                    $mail_msg = ';查看手机短信或登录邮箱查看验证码';
                } catch(Exception $e) {
                    //echo $e->getMessage();
                }
            }
            if($r==100) {
                echo '{"status":"ok","msg":"发送验证码成功！" '.$mail_msg.',"passport":"'.$mobile.'"}';
            }
            else {
                echo '{"status":"fail","msg":"对不起，短信服务器发生故障，造成的不便我们感到十分抱歉。请联系我们客服人员","code":'.$r.'}';
            }
        }
        else {
            echo '{"status":"fail","msg":"发送间隔太短！请在60秒后再重试"}';
        }
        break;
    case 'VerifyVcode':
        //$mobile = $_REQUEST['mobile'];
        //print_r($_SESSION);
        $vcode = strtolower($_REQUEST['vcode']);
        $now = $_SERVER['REQUEST_TIME'];
        if($now-$_SESSION['timer'] > 43200) {
            unset($_SESSION['vcode']);
        }
        if(isset($_SESSION['vcode'])
            && $vcode==$_SESSION['vcode']) {
            echo '{"status":"ok","msg":"验证通过！"}';
        }
        else {
            echo '{"status":"fail","msg":"验证失败"}';
        }
        break;
    case 'RelationshipCreate':
    case 'MemberRegister':
        // return false;
        $dataMain    = array();
        $dataExtInfo = array();
        $todo = $_REQUEST['actionType'];
        //TODO:注册验证码校验
        if($todo=='register' && trim($_POST['vcode']) != $_SESSION['vcode'] ) {
            exit('{"status":"fail","msg":"验证码错误！"}');
        }
        if(empty($_POST['username'])) {
            exit('{"status":"fail","msg":"姓名不能为空！","filed":"username"}');
        }
        $dataMain['cname'] = safetxt($_POST['username']);//联系人
        if(!is_chinese($dataMain['cname'])) {
            exit('{"status":"fail","msg":"姓名仅限中文汉字，请重新输入","filed":"username"}');
        }

		$dataMain['dname'] = safetxt($_POST['company']);//公司名
        /*if(!is_chinese($dataMain['dname']))*/
        if(empty($dataMain['dname'])) {
            exit('{"status":"fail","msg":"公司名称不能为空，请重新输入","filed":"company"}');
        }
        $dataMain['dtype'] = intval($_POST['dtype']);
        $dataMain['status'] = $dataMain['dtype']==0 ? 3 : 0;//供应商需审核
        $dataMain['mobile'] = safetxt($_POST['mobile']);
        if(isset($_POST['com_type'])) {
            $dataExtInfo['com_type'] = safetxt($_POST['com_type']);
        }
        else {
            $dataExtInfo['com_type'] = $dtype==1 ? safetxt($_POST['ctype1'])
                : safetxt($_POST['ctype0']);
        }
        if( $todo=='register' ) {
            if( !ismobile($dataMain['mobile']) ) {
                exit('{"status":"fail","msg":"手机号格式不正确","filed":"mobile"}');
            }
            $dataMain['alipay'] = safetxt($_POST['alipay']);
            /*2015-03-31 注册时不再必须输入支付宝
            if(!$dataMain['dtype']) {//供应商必填
                if(empty($dataMain['alipay'])) {
                    exit('{"status":"fail","msg":"支付宝账号为必填项！","filed":"alipay"}');
                }
            }
            */

            $dataExtInfo['license_no'] = safetxt($_REQUEST['license_no']);
            $dataExtInfo['sex'] = trim($_POST['sex']);//性别
        }
        else {
            if(!empty($dataMain['mobile']) && !ismobile($dataMain['mobile'])) {
                exit('{"status":"fail","msg":"手机号格式不正确","filed":"mobile"}');
            }
        }
        if( !empty($_REQUEST['g_tel']) ) {
            $ctel = safetxt($_REQUEST['g_tel']);
            $dataMain['ctel'] = isphone($ctel) ? $ctel :
                exit('{"status":"fail","msg":"固定电话格式不正确","filed":"g_tel"}');
        }
        if( !empty($_REQUEST['qq']) ) {
            $qq = safetxt($_REQUEST['qq']);
            $dataMain['qq'] = ctype_digit($qq) && strlen($qq)>4 ? $qq :
                exit('{"status":"fail","msg":"QQ号码格式不正确","filed":"qq"}');
        }
        $pwd_res=chkPassword($_POST['password'], $_POST['confirmPwd']);
        if($pwd_res!=1) {
            exit('{"status":"fail","msg":"'.$pwd_res.'","filed":"password"}');
        }
        if($_POST['password']!=$_POST['confirmPwd']) {
            exit('{"status":"fail","msg":"两次密码输入不正确，请重新输入密码！","filed":"password"}');
        }
        $dataMain['password'] = md5(md5($_POST['password']));
        // 邀请人
        $inviter = getDomainFid();
        if(!$inviter) $inviter = $_POST['inviter'];
        if($inviter){//邀请人都是帐号类型 在下面统一转换成ID
            $sql="SELECT id FROM pft_member WHERE account=$inviter LIMIT 1";
            $GLOBALS['le']->query($sql);
            $GLOBALS['le']->fetch_assoc();
            $dataMain['inviterID'] = $GLOBALS['le']->f('id');
        }
        

        $dataExtInfo['com_name'] = $dataMain['dname'];//公司
        $dataExtInfo['email']    = safetxt($_POST['email']);
        $result = $mem->register($dataMain, $dataExtInfo);
        if($todo=='CreateDistor' ) {
            $body = explode('|', $result['body']);
            if($result['status']=='ok'){
                $aname = $mem->getNameById($_SESSION['sid']);
                $s_r = array(
                    'search' => array('{dname}','{aname}','{pwd}'),
                    'replace' => array($dataMain['dname'],$aname,$_POST['password']),
                );
				
                SmsNotify::SendSMS($dataMain['mobile'],
                    SmsNotify::RELATION_SHIP_CREATE, $soap, $s_r);
                $exist_id = $body[0];
				
            } elseif($body[0]=='username') {
                $exist_id = $body[1];
                $msg = '您添加的分销商已经存在，系统已经为您建立供销关系。';
            }
			//员工添加的时候  获取公司ID
			$tmpId = $_SESSION['memberID'];
			//如果员工账号有权限添加需要拿到公司的ID
			if($_SESSION['dtype']==6){
				$sql = "SELECT parent_id FROM pft_member_relationship WHERE son_id = {$_SESSION['memberID']}";
				$GLOBALS['le']->query($sql);
				$GLOBALS['le']->fetch_assoc();
				$tmpId=$GLOBALS['le']->f("parent_id");
			}
			// print_r($_SESSION);
            $res = $mem->createRelationship($tmpId, $exist_id,0,0,$body[1]);
            if(isset($msg) && $res['status']=='ok') {
                $res['msg'] = $msg;
            }
            echo json_encode($res);
        }
        else {
            echo json_encode( $result );
        }
        break;
    case 'MemberRegisterEasy':
        //手机用户第一次下单时注册
        $dataMain    = array();
        $dataMain['mobile'] = $_POST['mobile'];
        $dataMain['dtype'] = 5;
        if( !ismobile($dataMain['mobile']) ) {
            exit('{"status":"fail","msg":"手机号格式不正确","filed":"mobile"}');
        }
        $pwd =   substr($dataMain['mobile'], 5 ,6);
        $dataMain['password'] = md5(md5($pwd));
        $result = $mem->register($dataMain);
        echo json_encode($result);
        break;
    case 'ResetPassword':
        $passport = safetxt($_REQUEST['passport']);
        $p1 = $_REQUEST['pass1'];
        $p2 = $_REQUEST['pass2'];
        $cp = chkPassword($p1, $p2);
        if($cp!=1) {
            $msg = '{"status":"fail","msg":"'.$cp.'"}';
        }
        else {
           $rs = $mem->resetPassword($passport,$p1, $GLOBALS['le']);
           $msg = $rs ? '{"status":"ok","msg":"密码重置成功"}'
                    :'{"status":"fail","msg":"'.$cp.'"}';
        }
        echo $msg;
        break;
    case 'GetMemList':
        //$mem = new MemberAccount($GLOBALS['le']);
        $ml = $mem->getMemList($_GET['mobile']);
//        print_r($ml);
        break;
    case 'GetMemShip':
        //$mem = new MemberAccount($GLOBALS['le']);
        $ml = $mem->gemMemShip();
        print_r($ml);
        break;
    case 'SearchDistor':
        $dname = safetxt($_REQUEST['dname']);
        $mode  = intval($_REQUEST['mode']);
        $dtype = 1;
        if(isset($_REQUEST['dtype'])) {
            $dtype = intval($_REQUEST['dtype']);
        }
        $res = $mem->chkDname($dname, $mode, $dtype);
        //echo( count(res) );
        if(empty($res)) {
            $a = array(
                'status'=>'fail',
                'msg'=>'不存在分销商',
                'body'=>''
            );
        }
        else {
            $a = array(
                'status'=>'ok',
                'msg'=>'存在分销商',
                'body'=>$res
            );
        }
        echo json_encode($a);
        break;
    case 'SearchDistor2':
        $dname = safetxt($_REQUEST['sname']);
        $memid = $_SESSION['memberID'];
        if(strlen($_REQUEST['company'])>0) {
            $com_type = "'','".str_replace('|','\',\'', rtrim($_REQUEST['company'],'|'))."'";
        }
		$search_type = $_REQUEST['search_type'] ? $_REQUEST['search_type']:'';
        echo json_encode($mem->SearchDistor($dname, '0,1', $memid,$com_type,'10'));
        break;
    case 'AddRelationShip':
        $distor_id = abs($_REQUEST['distor']);
		// 测试账号只能互加
		$test_account = eachOther_add_id();
		if(in_array($_SESSION['sid'],$test_account)){
			if(!in_array($distor_id,$test_account)){
				echo json_encode(array(
                    'status'=>'fail',
                    'msg'   =>'测试账号只允许添加以下账号:'.eachOther_add_dname(),
                    'body'  => ''
                ));
				exit;
			}
		}

        if(!chk_group($distor_id)){
            echo json_encode(array(
                'status'=>'fail',
                'msg'   =>'测试帐号和正式帐号不能互相添加',
                'body'  => ''
            ));
            exit;
        }


		// $tmpId = $_SESSION['memberID'];
		// if($_SESSION['dtype']==6){//如果员工账号有权限添加需要拿到公司的ID
			// $sql = "SELECT parent_id FROM pft_member_relationship WHERE son_id = {$_SESSION['memberID']}";
			// $GLOBALS['le']->query($sql);
			// $GLOBALS['le']->fetch_assoc();
			// $tmpId=$GLOBALS['le']->f("parent_id");
		// }
        // $res = $mem->createRelationship($tmpId, $distor_id);
        $res = $mem->createRelationship($_SESSION['sid'], $distor_id);
        echo json_encode($res);
        break;
    case 'SetMemStatus':
        try{
            echo json_encode($mem->StatusSet( $_POST['mid'], $_POST['status'], $_POST['rm_stuff']));
        } catch(Exception $e) {
            echo $e->getMessage();
        }
        break;
    /**
     * 管理员修改供应商企业名称
     */
    case 'DnameUpdate':
        if($_SESSION['dtype']!=9) exit('{"status":"fail","msg":"权限不够"');
		
		
		if(!isset($_POST['dname']) || $_POST['dname']=='') exit('{"status":"fail","msg":"公司名称不能为空"');		
		if(!isset($_POST['com_type']) || $_POST['com_type']=='') exit('{"status":"fail","msg":"企业名称不能为空"');
        $id = intval($_POST['id']);
        $com_type = safetxt($_POST['com_type']);
        $com_name = safetxt($_POST['com_name']);//企业名称
        $com_types = array('景区','酒店','旅行社','加盟门店','电商','旅行社','淘宝/天猫','其他','团购网');
        if(!in_array($com_type, $com_types)) {
            echo '{"status":"fail","msg":"企业类型错误，只能为【'.implode(',', $com_types).'】中的一个"}';
            exit;
        }
		
		// 验证名称唯一
		$sql = "select fid from pft_member_extinfo where com_name='$com_name' limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			if($GLOBALS['le']->f('fid')!=$id) exit('{"status":"fail","msg":"企业名称已存在"}');
		}
		
        $mem->updateMemberInfo(array(
            'com_type'      => $com_type,
            'com_name'      => $com_name,
            'add_saler_type'=> abs($_POST['ast']),
            'jiutian_auth'  => safetxt($_POST['jiutian_auth']),
            'refund_back'   => safetxt($_POST['refund_back'])),
            $id
		);
		
        $ma['dname'] = safetxt($_POST['dname']);
        $ma['group_id'] = abs($_POST['group_id']);
        if(!empty($_POST['dcode'])) $ma['dcode'] = safetxt($_POST['dcode']);
        echo json_encode($mem->updateMember($ma, $id));
        break;
    //设置淘宝ID
    case 'ApplyCreate':
        if(!empty($_REQUEST['coop'])) {
			
            $dtype = MemberAccount::TAO_APPLY;
        }
        else {
            $dtype = abs($_REQUEST['dtype']);
        }
        $data1 = safetxt($_REQUEST['coop']);
		
		
        echo json_encode($mem->ApplyCreate($dtype, $data1));
        break;
    case 'ApplyVerify':
        $status = intval($_REQUEST['status']);
        $log_id = intval($_REQUEST['log_id']);
        $msg = !empty($_REQUEST['msg']) ? safetxt($_REQUEST['msg']):null;
        $dtype = intval($_REQUEST['dtype']);
        $uid = intval($_REQUEST['uid']);
        echo json_encode($mem->ApplyVerify(new notice(), $uid, $log_id, $status, 1, $msg, $dtype));
        break;

    case 'MemberSearch':
        $token = md5(date('ymdH').'memsearch');
//        if(trim($_GET['token'])!=$token) {
//            exit;
//        }
        $req = safetxt($_GET['req']);
        $callBack = $_GET['jsonCallBack'];
        $sql = "SELECT id,dname,cname,account FROM pft_member WHERE ";
        if(is_numeric($req)) {
            $len = mb_strlen($req, 'UTF-8');
            if($len==6) {
                $sql .= " account='$req'";
            }
            elseif($len==11) {
                $sql .= " mobile='$req'";
            }
        }
        else {
            $sql .= " dname LIKE '%$req%'";
        }
        $mems = array();
        $GLOBALS['le']->query($sql);
        while($r=$GLOBALS['le']->fetch_assoc()) {
            $mems[] = $r;
        }
        echo $callBack.'('.json_encode($mems).')';
        break;
    case 'RelationHanler':
        if($_SESSION['dtype']!=9) {
            exit('权限不够！');
        }
        $action    = intval($_POST['handler']);
        $parent_id = intval($_POST['parent_id']);
        $son_id    = intval($_POST['son_id']);
        $ship_type = intval($_POST['ship_type']);
        echo json_encode($mem->RelationHanler($action,
            $parent_id,$son_id, $ship_type));
        break;
	case 'chkDname':
		$dname = trim($_REQUEST['dname']);
        $dname = safetxt($dname);
        $chk_res = $mem->chkDname($dname);
        if($chk_res){
            echo '{"status":"ok","msg":"存在该账号","mobile":"'.$chk_res.'"}';
	   }
        else {
            echo '{"status":"fail","msg":"不存在该账号"}';
        }
        break;
	//存在并获取分销商名称
	case 'chkAndGetDname':
		$dname = trim($_REQUEST['dname']);
        $dname = safetxt($dname);
        if($dname == $_SESSION['dname']){
            echo 
            exit;
        }
        $chk_res = $mem->chkDname($dname);
		// print_r($chk_res);
        if($chk_res){
			$memid = $_SESSION['sid'];
			$search_type = '';
			$r=$mem->_SearchDistor($dname, '0,1', $memid,null,$search_type);
			$chk_res=$r[0];
			$chk_res['ajaxStatus']=2;
			$chk_res['ajaxMsg']='存在该账号';
			$chk_res['ajaxMobile']=$chk_res['mobile'];
			echo json_encode($chk_res);
			exit;
	    }else{
            echo '{"ajaxStatus":"fail","reqMsg":"不存在该账号"}';
        }
        break;
	case 'chkAndGetDname_a':
		// 100 用户名可用
		// 101 不能添加自己为分销商
		// 102 用户名不可用
		$dname = $_REQUEST['dname'];
		if($dname == $_SESSION['dname']) exit('{"code":101,"mesg":"不能添加自己为分销商"}');
		
		// 检测是否存在
		$sql = "select m.id,m.dname,m.mobile,m.dtype,m.status,m.account as passport,m.cname,e.com_type from pft_member m,pft_member_extinfo e where m.dname='$dname' limit 1";
		$GLOBALS['le']->query($sql);
		if($data = $GLOBALS['le']->fetch_assoc()){
			// 联盟信息
			$sql = 'select id,protocol from pft_distributor_union_SE where fid="'.$data['id'].'" limit 1';
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
				$data['alliance'] = $GLOBALS['le']->f('id');
				$data['protocol'] = nl2br($GLOBALS['le']->f('protocol'));
				
			}
			
			// 分销关系
			if($data['dtype']==0 || $data['dtype']==1){
				$sid = $_SESSION['sid'];
				$sql = 'select id from pft_member_relationship where parent_id="'.$sid.'" and son_id="'.$data['id'].'" and status=0 limit 1';
				$GLOBALS['le']->query($sql);
				$data['created'] = ($GLOBALS['le']->fetch_assoc()) ? 1:0;
			}
			$data['code'] = 102;
			exit(json_encode($data));
		}else{
			exit('{"code":100}');
		}
		break;
	// 分销商模糊查询 author by Tong.BC
    //ctype_alpha 是否全部字母的判断 当是字母时 进行拼音首字母搜索的 zax
	case 'fuzzyGetDname':
		$dname = trim($_REQUEST['dname']);
		$dname = safetxt($dname);
		$r = $mem->fuzzySearchDistor($dname,'0,1',$_SESSION['sid'],null,ctype_alpha($dname));
		foreach($r as $key=>$row){
			// 联盟信息
			$sql = 'select id,protocol from pft_distributor_union_SE where fid="'.$row['id'].'" limit 1';
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
				$row['alliance'] = $GLOBALS['le']->f('id');
				$row['protocol'] = nl2br($GLOBALS['le']->f('protocol'));
				$r[$key] = $row;
			}
		}
		echo json_encode($r);
		break; 
    //管理员模糊查询供(0)销(1)商名称 用于saleproduct
    //2015-3-10更新 搜索分销商将在(0,1中搜索)
	case 'fuzzyGetDname_c':
		$dname = safetxt(trim($_REQUEST['dname'])); 
        $dtype = safetxt(trim($_REQUEST['dtype'])); 
        $dtype = $dtype=='1' ? $dtype = '0,1' :$dtype;
		$r = $mem->fuzzySearchDistor_c($dname,$dtype);
		echo json_encode($r);
		break;
        
     /*
    *新版分销商模糊查询  多了搜索强度的判断
    *@param int $add_saler_type
    *@by KaZeline zax 2015-1-6
    */
    case 'fuzzyGetDname_z':
        if(!$_SESSION['memberID']) exit('{"code":"102"}');
		$dname = trim($_REQUEST['dname']);
        if($dname == '') exit('[]');
		$dname = safetxt($dname);
        if( $_REQUEST['add_saler_type'] !=='1' && $_REQUEST['add_saler_type'] !=='0' )exit('非法搜索类型参数');
		$r = $mem->fuzzySearchDistor_z($dname,'0,1',$_SESSION['memberID'],null,$_REQUEST['add_saler_type'] );
		echo json_encode($r);
		break;
    //分销商手机搜索 by KaZeline Zax
    case 'mobileSearch':
        $sVal = trim($_REQUEST['mobile']);
		$sVal = safetxt($sVal);
        $r = $mem->searchDistorByM($sVal,'0,1',$_SESSION['memberID']);
		// print_r($r[]);
		if(isset($r[0]['id'])){// 存在分销商
			// 联盟信息
			$sql = 'select id,protocol from pft_distributor_union_SE where fid="'.$r[0]['id'].'" limit 1';
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
				$r[0]['alliance'] = $GLOBALS['le']->f('id');
				$r[0]['protocol'] = nl2br($GLOBALS['le']->f('protocol'));
			}
		}
        echo json_encode($r);
		break;
	// 申请绑定淘宝用户名 author by Tong.BC
	case 'bindTbSeller':
		$dtype = empty($_REQUEST['coop']) ? abs($_REQUEST['dtype']):MemberAccount::TAO_APPLY;
        $data1 = safetxt($_REQUEST['coop']);
		if(empty($data1)){
			echo json_encode(array('status'=>'err','msg'=>'淘宝账号不能为空'));
			exit;
		}
		
		// 唯一性判断
		$sql = "select id,id2 from pft_tb_bind where seller_nick='$data1' limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			if($GLOBALS['le']->f('id2')!=$_SESSION['sid']){
				exit('{"status":"fail","msg":"卖家账号已被绑定，请联系客服"}');
			}
		}
		$mem = new MemberAccount($GLOBALS['le'], $_SESSION['sid']);
        echo json_encode($mem->bindTbCreate($data1));
		break;
	// 审核绑定或取消或拒绝淘宝绑定
	case 'applyBindtb':
        $log_id = intval($_REQUEST['log_id']);// 绑定淘宝表ID
        $msg = !empty($_REQUEST['msg']) ? safetxt($_REQUEST['msg']):null;// 拒绝理由
        $uid = intval($_REQUEST['uid']);// 分销商ID
        $status = intval($_REQUEST['status']);// 状态 1为审核 0为拒绝并清空淘宝账号 
		$Msg = array('解除','审核','拒绝');
		$eMsg = $Msg[$status];
        if($mem->applyBindtb(new notice(),$uid,$log_id,$status,$msg)){
			echo json_encode(array('s'=>'success','msg'=>$eMsg.'成功'));
			exit;
		}
		echo json_encode(array('s'=>'error','msg'=>$eMsg.'失败'));
		break;
    case 'SearchProviders':
        $name = safetxt($_REQUEST['dname']);
        $Providers = $mem->ApplyerList($name);
        if (is_array($Providers) && count($Providers)>0) {
            echo json_encode($Providers);
        }
        break;
	// 资质认证审核
	case 'accredits_auth':
		$did   = $_POST['did'] + 0;
		$state = $_POST['status'] + 0;
		$msg   = $_POST['msg'];
		// 身份认证
		if($_SESSION['sid']!=1) exit('{"status":"fail","msg":"身份不合法"}');
		if($did==0) exit('{"status":"fail","msg":"参数错误"}');
		if($state==2){// 通过审核
			$sql = "update pft_member_extinfo set certi_status=2 where fid=$did and certi_status=0 limit 1";
			// if($GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"操作成功"}');
			echo $sql;
			exit('{"status":"success","msg":"操作成功"}');
		}
		
		if($state==3){// 拒绝通过
			$sql = "update pft_member_extinfo set certi_status=3,ref_reason='$msg' where fid=$did and certi_status=0 limit 1";
			// if($GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"操作成功"}');
			echo $sql;
			exit('{"status":"success","msg":"操作成功"}');
		}
		exit('{"status":"fail","msg":"操作失败"}');
		break;
    default:break;
}

function getDomainFid(){
    $exist = array(
        'paypiao.12301.cc'=>'200489',
        'www.paypiao.cn'=>'200489',
        'syyry.12301.cc'=>'200514',
        'www.syyry.net'=>'200514',
        'dtdc.12301.cc'=>'100092',
        'fxxt.dtdc.org.cn'=>'100092',
        'freeu.12301.cc'=>'',
        'www.freeu.cn'=>'',
        'smf.12301.cc'=>'100110',
        'trfenxiao.12301.cc'=>'100069',
        'www.trfenxiao.com'=>'100069',
        'hubei.12301.cc'=>'200181',
        'jqzj.12301.cc'=>'502145',
        'yyxpiao.12301.cc'=>'123552',
        'mp.yyx.com.cn'=>'123552',
        'huangshan.12301.cc'=>'123605',
        'hjzl.12301.cc'=>'123682',
        'ty.369trip.cn'=>'123682',
        'douqu.12301.cc'=>'123662',
        'www.douqu.com'=>'123662',
        'okpiao.12301.cc'=>'123707',
        'okpiao.com.cn'=>'123707',
    );
    $SERVER_NAME = $_SERVER['SERVER_NAME'];
    //2015-05-18 联盟邀请人 zax
    if(!$exist[$SERVER_NAME]){
        switch ($_SERVER['HTTP_REFERER']) {
        	case 'http://www.12301.cc/register.html':
                $exist[$SERVER_NAME] = 123666;
        		break;
            case 'http://www.12301.cc/distributor_add.html':
                $exist[$SERVER_NAME] = $_SESSION['saccount'];
                break;
        	default:
                if(!strpos($_SERVER['HTTP_REFERER'],'register')) break;
                $host = str_replace('http://www.', '', $_SERVER['HTTP_REFERER']);
                $domain   = substr($host, 0, strpos($host, '.12301'));//店主帐号
                if($domain=='') break;
                include_once '/var/www/html/new/d/module/zax/ip/ip.php';
                $exist[$SERVER_NAME] = ip_inviterID($domain);
        		break;
        }
    }

    return $exist[$SERVER_NAME];
}
// 测试账号只允许互加
function eachOther_add_id(){
	return array(58,94,1589,1632,2092,2152,3623);
	// return array();
}
function eachOther_add_dname(){
	return '测试10,测试8,天地会,完成测试壹号,测试六,分销测试账号公司,测试分销商,我爱测试';
}

function chk_group($did){
    $sql ="select group_id from pft_member where id in($did,{$_SESSION['sid']}) limit 2";
    $GLOBALS['le']->query($sql);
    $GLOBALS['le']->fetch_assoc();
    $g = $GLOBALS['le']->f('group_id');
    $GLOBALS['le']->fetch_assoc();
    $s = $GLOBALS['le']->f('group_id');
	// return true;
    return (($g ==3 && $s ==3) || ($g ==2 && $s ==2) ||
        ($g !=2 && $s !=2 && $g !=3 && $s !=3));
    //true 表示 添加者和被添加者 同为测试帐号/点餐组 或 同为正式帐号
}

?>
